import { encryptData, decryptData } from './index'

const TOKEN_KEY = 'inOrderFood-token'
const EXPIRY_DAYS = 15

export const setToken = (token: string) => {
  localStorage.setItem(TOKEN_KEY, token)
}

export const getToken = () => {
  return localStorage.getItem(TOKEN_KEY)
}

export const clearToken = () => {
  localStorage.removeItem(TOKEN_KEY)
}

export const hasToken = () => {
  return !!getToken()
}

// 保存登录账号
export const saveLoginAccount = (account: string, password: string) => {
  console.log('saveLoginAccount', account, password)
  const loginInfo = {
    account,
    password: encryptData(password),
    saveTime: Math.floor(Date.now() / 1000)
  }
  localStorage.setItem('userAccount', JSON.stringify(loginInfo))
}

export const getLoginAccount = (): { account: string; password: string } | null => {
  const stored = localStorage.getItem('userAccount')
  if (!stored) return null

  try {
    const user = JSON.parse(stored)
    const now = Math.floor(Date.now() / 1000)
    const expiryTime = EXPIRY_DAYS * 24 * 60 * 60
    if (now - user.saveTime > expiryTime) {
      localStorage.removeItem('userAccount')
      return null
    }
    return {
      account: user.account,
      password: decryptData(user.password)
    }
  } catch (err) {
    localStorage.removeItem('userAccount')
    return null
  }
}

export const clearLoginAccount = () => {
  localStorage.removeItem('userAccount')
}
